package com.scalar.forecast.systemprefs.dao;

import com.scalar.ScalarException;

import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DataSource;
import com.scalar.forecast.systemprefs.SystemPreferences;
import com.scalar.forecast.utils.ForecastSqlQueryMappings;
import com.scalar.forecast.utils.VOUtils;

import com.scalar.forecast.commons.logger.Logger;
import com.scalar.forecast.commons.logger.LoggerManager;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: Feb 12, 2005
 * Time: 1:08:52 PM
 * To change this template use File | Settings | File Templates.
 */

public class SystemPrefsDAO
{
    private static final Logger LOGGER = LoggerManager.getLogger( SystemPrefsDAO.class );

    /**
     * This method saves the SystemPreferences Details
     *
     * @param dbTransaction
     * @param systemPreferences
     * @throws com.scalar.ScalarException
     */

    public static void saveSystemPeferences( DBTransaction dbTransaction,  com.scalar.forecast.systemprefs.SystemPreferences systemPreferences, String userId ) throws ScalarException
    {

        Connection conn = null;
        CallableStatement cstmt = null;
        boolean success = false;
        try
        {
            if( dbTransaction != null )
            {
                conn = dbTransaction.getConnection();
            }
            else
            {
                conn = DataSource.getConnection();
            }

            cstmt = conn.prepareCall( ForecastSqlQueryMappings.get( "systemPreferences.saveSystemPrferences" ) );
            LOGGER.log( Logger.DEBUG, "Query is : " + ForecastSqlQueryMappings.get( "systemPreferences.saveSystemPrferences" ) );

            cstmt.setInt( 1, Integer.parseInt( systemPreferences.getCanBuildMasterCanOverrideSFC() ) );
            cstmt.setInt( 2, Integer.parseInt( systemPreferences.getPartNumberType() ) );
            cstmt.setInt( 3, Integer.parseInt( systemPreferences.getPriceType() ) );

            cstmt.setString( 4 , userId );
            cstmt.registerOutParameter( 5, java.sql.Types.INTEGER );
            cstmt.executeUpdate();
            int errorCode = cstmt.getInt( 5 );
            if( errorCode == 0 )
            {
                success = true;
            }
            else
            {
                success = false;
                LOGGER.log( Logger.ERROR, "Error while updating SystemPreferences " );
                throw new ScalarException( "Could not update  SystemPreferences  in database " );
            }
        }
        catch( Throwable th )
        {
            LOGGER.log( Logger.ERROR, "Error while updating SystemPreferences ", th );
            throw new ScalarException( "Could not update  SystemPreferences  in database ", th );
        }
        finally
        {
            if( dbTransaction == null )
            {
                if( conn != null )
                {
                    if( success )
                    {
                        try
                        {
                            conn.commit();
                        }
                        catch( Throwable th )
                        {
                            LOGGER.log( Logger.ERROR, "Error while Commiting the save SystemPreferences", th );
                            throw new ScalarException( "Error while Commiting the save SystemPreferences", th );
                        }
                    }
                    else
                    {
                        try
                        {
                            conn.rollback();
                        }
                        catch( Throwable th )
                        {
                            LOGGER.log( Logger.ERROR, "Error while rolling back the save SystemPreferences", th );
                            throw new ScalarException( "Error while rolling back the save SystemPreferences", th );
                        }
                    }
                }
            }
            if( cstmt != null )
            {
                try
                {
                    cstmt.close();
                }
                catch( Throwable th )
                {
                    LOGGER.log( Logger.ERROR, "Error while closing the statement in save SystemPreferences", th );
                }
            }
            if( conn != null )
            {
                try
                {
                    conn.close();
                }
                catch( Throwable th )
                {
                    LOGGER.log( Logger.ERROR, "Error while closing the connection in SystemPreferences",th );
                }
            }
        }
    }

     /**
      * Loads the system preferences pertaining
      *
      * @return
      * @throws ScalarException
      */
    public static SystemPreferences loadSystemPreferences() throws ScalarException
    {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        SystemPreferences localSystemPreferences = new SystemPreferences();

        try
        {

            conn = DataSource.getConnection();
            pstmt = conn.prepareCall( ForecastSqlQueryMappings.get( "systemPreferences.loadSystemPrferences" ) );
            LOGGER.log( Logger.DEBUG, "Query is : " + ForecastSqlQueryMappings.get( "systemPreferences.loadSystemPrferences" )   );
            rs = pstmt.executeQuery();
            if ( rs.next() )
            {
                localSystemPreferences.setSystemPrefId( rs.getInt( "SYSTEMPRFID" ) );

                localSystemPreferences.setCanBuildMasterCanOverrideSFC(String.valueOf( rs.getInt( "BUILD_MASTER_CAN_OVERRIDE_SFC" ) ) ) ;
                localSystemPreferences.setPartNumberType(String.valueOf( rs.getInt( "PART_NUMBER_TYPE" ) ) );
                localSystemPreferences.setPriceType(String.valueOf( rs.getInt( "PRICE_PULL" ) ) );

                localSystemPreferences.setModifeidBy( rs.getString( "MODIFIED_BY" ) ) ;
                localSystemPreferences.setModifiedOn( rs.getString( "MODIFIED_ON" ) );

                VOUtils.setSystemPreferencesNullValuesToEmpty( localSystemPreferences );
            }
        }

        catch( Throwable th )
        {
            LOGGER.log( Logger.ERROR, "Error while loading SystemPreferences ", th );
            throw new ScalarException( "Could not Load SystemPreferences", th );
        }

        finally
        {
            if( rs != null )
            {
                try
                {
                    rs.close();
                }
                catch( Throwable th )
                {
                    LOGGER.log( Logger.DEBUG, "Error while closing the result set in Load SystemPreferences " );
                }
            }
            if( pstmt != null )
            {
                try
                {
                    pstmt.close();
                }
                catch( Throwable th )
                {
                    LOGGER.log( Logger.DEBUG, "Error while closing the statement in Load SystemPreferences " );
                }
            }
            if( conn != null )
            {
                try
                {
                    conn.close();
                }
                catch( Throwable th )
                {
                    LOGGER.log( Logger.DEBUG, "Error while closing the connection in Load SystemPreferences " );
                }
            }
        }

        return localSystemPreferences;

    }

}
